<!--富文本编辑器-->
<template>
  <div class="rich-text-editor-container" v-loading="loading">
    <!-- 图片上传组件辅助，组件内添加v-show=“false”属性，把该组件隐藏起来。-->
    <!-- <el-upload class="avatar-uploader" :action="uploadUrl" name="img" :show-file-list="false" :on-success="uploadSuccess"
      :on-error="handleUploadError" :headers="headers" :before-upload="beforeUpload" ref="upload">
    </el-upload> -->
    <el-upload class="avatar-uploader" :id="refValueEditor" :action="uploadUrl" :before-upload="beforeUpload"
      :on-success="uploadSuccess" :on-error="handleUploadError" name="file" :show-file-list="false" :headers="headers"
      style="display: none" ref="upload" :limit="limit" v-if="this.type == 'url'" :key="randomId(3)">
    </el-upload>
    <quill-editor :content="content" :options="editorOptions" class="ql-editor" :ref="refValueEditor" :id="randomId(3)"
      @change="onEditorChange($event)" @click.native="handleEditAblequestion">
    </quill-editor>
    <!--视频上传弹窗-->
    <div>
      <el-dialog :close-on-click-modal="false" width="50%" style="margin-top: 1px" title="视频上传"
        :visible.sync="videoForm.show" append-to-body>
        <el-tabs v-model="videoForm.activeName">
          <el-tab-pane label="添加视频链接" name="first">
            <el-input v-model="videoForm.videoLink" placeholder="请输入视频链接" clearable></el-input>
            <el-button type="primary" size="small" style="margin: 20px 0px 0px 0px "
              @click="insertVideoLink(videoForm.videoLink)">确认
            </el-button>
          </el-tab-pane>
          <el-tab-pane label="本地视频上传" name="second">
            <el-upload v-loading="loading" style="text-align: center;" drag :action="uploadVideoConfig.uploadUrl"
              :headers="headers" :before-upload="onBeforeUploadVideo" :on-success="onSuccessVideo"
              :on-error="onErrorVideo" :multiple="false" :show-file-list="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传MP4文件，且不超过{{ uploadVideoConfig.maxSize }}M</div>
            </el-upload>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>
<script>
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor, Quill } from 'vue-quill-editor'
import { getToken } from "@/utils/auth";

// 设置title
import { setQuillTitle } from './quill-title';
// 这里引入修改过的video模块并注册
import Video from './quill-video';
Quill.register(Video, true)

// 工具栏
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["image", "video"]// 链接、图片、视频 // 视频
]
export default {
  name: 'RichTextEditor',
  components: {
    quillEditor
  },
  props: {
    /* 编辑器的索引 */
    quillIndex: {
      type: Number,
      default: 0
    },
    /*编辑器的ref */
    refValue: {
      type: String,
      default: "myrefValue",
    },
    /* 类型（base64格式、url格式） */
    type: {
      type: String,
      default: "url",
    },
    /* 限制数量 */
    limit: {
      type: Number,
      default: 20,
    },
    /* 编辑器的内容 */
    content: { // 返回的html片段
      type: String,
      default: ''
    },
    // 视频上传配置
    uploadVideoConfig: {
      type: Object,
      default() {
        return {
          uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传地址
          maxSize: 10, // 图片上传大小限制，默认不超过2M
          // name: 'Filedata' // 图片上传字段
        }
      }
    }
  },
  data() {
    let _self = this;
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      loading: false, // 加载loading
      editorOptions: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'video': () => {
                // 覆盖默认的上传视频，点击视频图标，显示弹窗
                _self.videoForm.show = true
              },
              image: (value) => {
                if (value) {
                  // 调用element的图片上传组件
                  document.querySelectorAll(".avatar-uploader input")[this.quillIndex].click();
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      // 视频上传变量
      videoForm: {
        show: false, // 显示插入视频链接弹框的标识
        videoLink: '',
        activeName: 'first'
      },
      refValueEditor: '',
      qillInit: true
    }
  },
  created() {
    this.refValueEditor = this.refValue;
  },
  mounted() {
    // 初始给编辑器设置title
    setQuillTitle()
    this.$refs[`${this.refValueEditor}`].quill.enable(false);
  },
  methods: {
    handleEditAblequestion() {
      if (this.qillInit) {
        this.$refs[`${this.refValueEditor}`].quill.enable(true);
        this.qillInit = false
      }
      this.$refs[`${this.refValueEditor}`].quill.focus();
    },
    randomId(len) {
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
      var tempLen = chars.length, tempStr = '';
      for (var i = 0; i < len; ++i) {
        tempStr += chars.charAt(Math.floor(Math.random() * tempLen));
      }
      return tempStr;
    },
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    beforeUpload(file) { },
    uploadSuccess(res) {
      // 获取富文本组件实例
      let quill = this.$refs[`${this.refValueEditor}`].quill
      // // 如果上传成功 
      if (res.code == 200) {
        // 获取光标所在位置
        let length = quill.getSelection() ? quill.getSelection().index : 0;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', res.url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
        this.$message.error('图片插入失败！')
      }
    },
    // 文本编辑
    onEditorChange({ quill, html, text }) {
      // console.log('editor changed:', html)
      // console.log('html.replace(/<[^>]*>|/g:', html.replace(/<[^>]*>|/g))
      // let newHtml = html?.replaceAll('<img ','<img class="editor-img" ');
      this.$emit('update:content', html)
      this.$emit('input', html)
    },
    hideLoading() {
      this.loading = false
    },
    /** --------- 视频上传相关 start ---------  */
    insertVideoLink(videoLink, poster) {
      if (!videoLink) return this.$message.error('视频地址不能为空！')
      this.videoForm.show = false
      let quill = this.$refs[`${this.refValueEditor}`].quill
      // 获取编辑器光标位置
      let index = quill.selection.savedRange.index;
      // 没有视频默认封面时，设置默认视频封面图片
      const img = poster ? poster : ''
      // 在光标所在位置 插入视频
      quill.insertEmbed(index, 'video', {
        url: videoLink,
        poster: img
      })
      // 调整光标到最后
      quill.setSelection(index + 1)
    },
    // el-文件上传组件
    onBeforeUploadVideo(file) {
      this.loading = true
      let acceptArr = ['video/mp4']
      const isVideo = acceptArr.includes(file.type)
      const isLt1M = file.size / 1024 / 1024 < this.uploadVideoConfig.maxSize
      if (!isVideo) {
        this.hideLoading()
        this.$message.error('只能上传mp4格式文件!')
      }
      if (!isLt1M) {
        this.hideLoading()
        this.$message.error(`上传文件大小不能超过 ${this.uploadVideoConfig.maxSize}MB!`)
      }
      return isLt1M && isVideo
    },
    // 文件上传成功时的钩子
    onSuccessVideo(res) {
      this.hideLoading()
      if (res.code === 200) {
        this.insertVideoLink(res.url)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 文件上传失败时的钩子
    onErrorVideo() {
      this.hideLoading()
      this.$message.error('上传失败')
    },
    /**--------- 视频上传相关 end --------- */
  }
}
</script>
<style  lang='scss'>
.ql-editor .ql-video {
  display: block;
  width: 80%;
  height: 300px;
  max-width: 100%;
}

.rich-text-editor-container .ql-container {
  min-height: 300px;
}

.rich-text-editor-container .ql-editor {
  padding: 0;
}

.rich-text-editor-container .ql-tooltip {
  left: 5px !important;
}
</style>